package com.phoenix.callAnalysis;

import java.util.ArrayList;

import com.phoenix.callAnalysis.db.MyCallLog;
import com.phoenix.callAnalysis.db.MyDB;
import com.phoenix.callAnalysis.models.Constants;
import com.phoenix.callAnalysis.models.LoadDataFlag;
import com.phoenix.callAnalysis.models.MyCall;
import com.phoenix.callAnalysis.utils.Utils;

import android.app.Activity;
import android.app.Application;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * variable needed in Application: EULA, language
 * 
 * @author Phoenix
 * 
 */
public class CallAnalysisApplication extends Application {

	public static final String TAG = CallAnalysisApplication.class
			.getSimpleName();

	public static ArrayList<MyCall> mCallsList;
	public static String language;
	public static SharedPreferences mPreferences;
	public static MyDB myDB;
	public static LoadDataFlag needLoadData = LoadDataFlag.NO_NEED;
	public static MyCallLog myCallLog;
	public static Utils mUtils;
	public static int dataSource = Constants.DATASOURCE_SYSTEM;

	@Override
	public void onCreate() {
		super.onCreate();
		// get preferences
		mPreferences = getSharedPreferences(Constants.CALL_PREFERENCES,
				Activity.MODE_PRIVATE);

		// get myDB
		myDB = new MyDB(this);
		myDB.open();

		// check if the first use
		if (!mPreferences.getBoolean(Constants.CALL_PREFERENCES_EULA_ACCEPTED,
				false)) {
			needLoadData = LoadDataFlag.FIRST_USE;
		} else {
			// check if there is calls data
			int count = myDB.getCallsCount();
			if (count == -1) {
				Log.e(TAG, ".getCallsCount() ERROR!");
			} else if (count == 0) {
				needLoadData = LoadDataFlag.NO_DATA;
			}
		}
		// get language
		if (mPreferences.contains(Constants.CALL_PREFERENCES_LANGUAGE)) {
			language = mPreferences.getString(
					Constants.CALL_PREFERENCES_LANGUAGE,
					Constants.CALL_PREFERENCES_LANGUAGE_DEFAULT);
		} else {
			Log.d(TAG, getResources().getConfiguration().locale.getLanguage());
			if (getResources().getConfiguration().locale.getLanguage().equals(
					Constants.CALL_PREFERENCES_LANGUAGE_ZH)) {
				mPreferences
						.edit()
						.putString(Constants.CALL_PREFERENCES_LANGUAGE,
								Constants.CALL_PREFERENCES_LANGUAGE_ZH)
						.commit();
				language = Constants.CALL_PREFERENCES_LANGUAGE_ZH;
			} else {
				mPreferences
						.edit()
						.putString(Constants.CALL_PREFERENCES_LANGUAGE,
								Constants.CALL_PREFERENCES_LANGUAGE_EN)
						.commit();
				language = Constants.CALL_PREFERENCES_LANGUAGE_EN;
			}
		}
		
		// get myCallLog
		myCallLog = new MyCallLog(this);
		
		//get Utils
		mUtils = new Utils(this);
	}

	@Override
	public void onTerminate() {
		myDB.close();
		super.onTerminate();
	}

}
